package com.pj.utils;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.pj.utils.cache.RedisUtil;

import java.io.ByteArrayOutputStream;
import java.util.Base64;
import java.util.UUID;

public class CaptchaRedisUtil {

    /**
     * 生成验证码并存储到 Redis，返回验证码图片和存储在 Redis 中的键
     */
    public static CaptchaInfo generateCaptcha() {
        // 定义图形验证码的长和宽
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100);

        // 重新生成验证码
        lineCaptcha.createCode();
        // 新的验证码
        String code = lineCaptcha.getCode();

        // 将验证码存储到 Redis，生成 Redis 中的键
        String captchaKey = "CAPTCHA_" + UUID.randomUUID().toString(); // 生成唯一键
        RedisUtil.setByMINUTES(captchaKey, code, 5); // 假设验证码有效期为5分钟

        // 获取验证码图片的 BASE64 编码
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        lineCaptcha.write(outputStream);
        String base64Image = Base64.getEncoder().encodeToString(outputStream.toByteArray());

        return new CaptchaInfo("data:image/png;base64," + base64Image, captchaKey);
    }

    /**
     * 验证验证码是否正确
     */
    public static boolean verifyCaptcha(String captchaKey, String userInput) {
        String captchaValue = RedisUtil.get(captchaKey); // 从 Redis 获取验证码

        // 验证用户输入的验证码是否正确
        boolean isValid = captchaValue != null && captchaValue.equals(userInput);

        // 如果验证成功，从缓存中删除验证码
        if (isValid) {
            RedisUtil.del(captchaKey); // 从Redis中删除验证码
        }

        return isValid;
    }

    public static class CaptchaInfo {
        private final String captchaImage;
        private final String captchaKey;

        public CaptchaInfo(String captchaImage, String captchaKey) {
            this.captchaImage = captchaImage;
            this.captchaKey = captchaKey;
        }

        public String getCaptchaImage() {
            return captchaImage;
        }

        public String getCaptchaKey() {
            return captchaKey;
        }
    }
}
